package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.reflect.TypeToken
import com.jakewharton.rxbinding2.view.RxView
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.permission.PermissionUtils
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.PayButton
import com.two.screen.water.balance.bean.database.OrderDB
import com.two.screen.water.balance.bean.database.OrderDBDao
import com.two.screen.water.balance.bean.database.OrderProductDB
import com.two.screen.water.balance.bean.database.ServerOrderResult
import com.two.screen.water.balance.listener.MyObserver
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.NormalApi
import com.two.screen.water.balance.net.api.OrderApi
import com.two.screen.water.balance.net.api.OrderApi.ORDER_STATUS_PAID
import com.two.screen.water.balance.net.api.OrderApi.ORDER_STATUS_PAYING
import com.two.screen.water.balance.net.api.OrderApi.ORDER_TYPE_NORMAL
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_CASH
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_NONE
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.net.observer.NormalObserver
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.bean.PrintOrderBean
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.widget.DividerItemDecoration
import com.two.screen.water.balance.widget.dialog.ChooseDateDialog
import com.two.screen.water.balance.widget.keyboard.flow.KeyboardUtilFlow
import com.two.screen.water.balance.widget.keyboard.flow.MyKeyBoardViewFlow
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.activity_order_local.*
import org.greenrobot.greendao.query.WhereCondition
import java.util.concurrent.TimeUnit

/*历史订单、本地订单*/
@Route(path = ARouterUtils.OrderLocalActivity)
class OrderLocalActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_order_local
    val mFloatTag = "大家好，我是渣渣昆"
    private var mKeyboardUtilFlow: KeyboardUtilFlow? = null

    lateinit var mSearchAdapter: SearchAdapter
    lateinit var mProductAdapter: ProductAdapter
    private var mCurOrderDB: OrderDB? = null

    private var mIsShowFilter: Boolean = false

    /*条件查询*/
    private var mChooseDateDialog: ChooseDateDialog? = null
    private var mDateBegin: String? = null
    private var mDateEnd: String? = null
    private var mSearchDay = 0
    private var mPage = 0 //从
    private var mPageSize = 100 // 一页有几条
    private var mCurStateUpload = -1//上传状态
    private var mCurStatePay = 0//支付状态
    private var mCurPayType = -1//支付类型


    override fun initView(savedInstanceState: Bundle?) {
        initSearchRecyclerView()
        initProductRecyclerView()
        initFilter()
    }

    private fun initFilter() {
        if (mIsShowFilter) {
            mFilterIv.setImageResource(R.drawable.ic_keyboard_arrow_down_grey_cfcdcd)
            mFilterLayout.visibility = View.VISIBLE
        } else {
            mFilterIv.setImageResource(R.drawable.ic_keyboard_arrow_down_white)
            mFilterLayout.visibility = View.GONE
        }
    }

    private fun initSearchRecyclerView() {
        (mSearchRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mSearchRecyclerView?.addItemDecoration(
            DividerItemDecoration(
                this, DividerItemDecoration.HORIZONTAL_LIST,
                resources.getDimension(R.dimen.common_measure_1dp).toInt(),
                ContextCompat.getColor(App.context!!, R.color.c6), true
            )
        )
        mSearchAdapter = SearchAdapter()
        mSearchRecyclerView.layoutManager = LinearLayoutManager(this)
        mSearchRecyclerView.adapter = mSearchAdapter
        mSearchAdapter.bindToRecyclerView(mSearchRecyclerView)
        mSearchAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    private fun initProductRecyclerView() {
        (mProductRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mProductAdapter = ProductAdapter()
        mProductRecyclerView.layoutManager = LinearLayoutManager(this)
        mProductRecyclerView.adapter = mProductAdapter
        mProductAdapter.bindToRecyclerView(mProductRecyclerView)
        mProductAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    override fun initData() {
        getOrderDBList()
    }

    //获取订单数据
    private fun getOrderDBList(isRefresh: Boolean = true) {
        if (isRefresh) mPage = 0

        var userId = DataApi.mUserId
        val keyName = mSearchMulEt.text.trim()
        var list = arrayListOf(OrderDBDao.Properties.OrderSn.like("%$keyName%"))//模糊搜索查询
        d("mCurStateUpload:$mCurStateUpload,mCurStatePay:$mCurStatePay,mCurPayType:$mCurPayType")
        //上传状态
        if (mCurStateUpload != -1) {
            list.add(OrderDBDao.Properties.UploadStatus.eq(mCurStateUpload)) //等于
        }
        //支付状态
        if (mCurStatePay != 0) {
            list.add(OrderDBDao.Properties.OrderStatus.eq(mCurStatePay)) //等于
        }
        //支付类型
        if (mCurPayType != -1) {
            list.add(OrderDBDao.Properties.PayType.eq(mCurPayType)) //等于
        }

        var startTime = CommUtils.YMD2s(mDateBegin) ?: 0L
        var endTime = CommUtils.YMD2s(mDateEnd) ?: 0L
        var time = CommUtils.YMD2s(CommUtils.toYMD(System.currentTimeMillis() / 1000, "yyyy-MM-dd")) ?: 0L
        d("mSearchDay:$mSearchDay,startTime:$startTime,endTime:$endTime,time:$time")
        when {
            //今天
            mSearchDay == 1 -> {
                list.add(OrderDBDao.Properties.PayTime.ge(time)) //大于
                list.add(OrderDBDao.Properties.PayTime.le(time + 24 * 3600 - 1)) //小于
                d("今天：${time + 24 * 3600 - 1}")
            }
            //近3天
            mSearchDay == 3 -> {
                list.add(OrderDBDao.Properties.PayTime.ge(time - 2 * 24 * 3600)) //大于
                list.add(OrderDBDao.Properties.PayTime.le(time + 24 * 3600 - 1)) //小于
                d("近3天：${time - 2 * 24 * 3600}")
                d("近3天：${time + 24 * 3600 - 1}")
            }
            //近七天
            mSearchDay == 7 -> {
                list.add(OrderDBDao.Properties.PayTime.ge(time - 6 * 24 * 3600)) //大于
                list.add(OrderDBDao.Properties.PayTime.le(time + 24 * 3600 - 1)) //小于
                d("近七天：${time - 6 * 24 * 3600}")
                d("近七天：${time + 24 * 3600 - 1}")
            }
            //日期选择 筛选
            startTime > 0 && endTime > 0 -> {
                list.add(OrderDBDao.Properties.PayTime.ge(startTime)) //大于
                list.add(OrderDBDao.Properties.PayTime.le(endTime + 24 * 3600 - 1)) //小于
                d("日期选择：${startTime}")
                d("日期选择：${endTime + 24 * 3600 - 1}")
            }
        }
        list.add(OrderDBDao.Properties.OrderType.eq(ORDER_TYPE_NORMAL)) //订单
        list.add(OrderDBDao.Properties.UserId.eq(userId)) //用户id
        Observable.create(ObservableOnSubscribe<MutableList<OrderDB>> { e ->
            val orderDBList = App.mDaoMaster?.newSession()?.queryBuilder(OrderDB::class.java)
                ?.where(WhereCondition.StringCondition("1=1"), *list.toTypedArray())
                ?.orderDesc(OrderDBDao.Properties.PayTime)
                ?.offset(mPage * mPageSize)?.limit(mPageSize)
                ?.list()?.toMutableList()
            if (orderDBList != null) {
                e.onNext(orderDBList)
            } else e.onError(Throwable("暂无数据"))
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this))
            .subscribe(object : MyObserver<MutableList<OrderDB>>() {
                override fun onNext(list: MutableList<OrderDB>) {
                    var tmpList = mutableListOf<OrderDB>()
                    //d("list:${list.size};mCurStateUpload:${mCurStateUpload};mCurStatePay:${mCurStatePay};mCurPayType:${mCurPayType};")
                    list.forEach {
                        if (mCurStateUpload == -1 && mCurStatePay == 0 && mCurPayType == -1) {
                            //如果触发了筛选就优先走筛选。
                            if ((PAY_TYPE_NONE.toString() != it.payType && PAY_TYPE_CASH.toString() != it.payType) && it.uploadStatus != 1) {
                                // 除了现金过滤掉其他支付类型未上传
                            } else {
                                tmpList.add(it)
                            }
                        } else {
                            tmpList.add(it)
                        }

                    }
                    if (isRefresh) {
                        tmpList.forEach { it.item_type = 0 }
                        var first = tmpList.firstOrNull()
                        first?.item_type = 1
                        setData(true, tmpList)
                        //TODO:刷新右边显示
                        updateOrderInfo(first)
                    } else {
                        tmpList.forEach { it.item_type = 0 }
                        setData(false, tmpList)
                    }
                }

                override fun onError(t: Throwable) {
                    ToastUtil.showToast(t.message.toString())
                }
            })
    }

    private fun setData(isRefresh: Boolean, data: MutableList<OrderDB>?) {
        mPage++
        val size = data?.size ?: 0
        if (isRefresh) {
            mSearchAdapter.setNewData(data)
        } else {
            if (size > 0) {
                mSearchAdapter.addData(data!!)
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mSearchAdapter.loadMoreEnd(isRefresh)
        } else {
            mSearchAdapter.loadMoreComplete()
        }
    }

    @SuppressLint("ClickableViewAccessibility", "CheckResult", "SetTextI18n")
    override fun initListener() {
        mSearchAdapter.setOnLoadMoreListener({ loadMore() }, mSearchRecyclerView)
        mGoBackLayout.setOnClickListener { goBack() }
        mFilterIv.setOnClickListener { }
        mSearchMulEt.setOnClickListener { }

        mSearchMulEt.setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                initEasyFloat()
            }
            false
        }
        mFilterIv.setOnClickListener {
            mIsShowFilter = !mIsShowFilter
            initFilter()
        }
        mTodaySearchTv.setOnClickListener {
            updateSearchDayUI(mTodaySearchTv, 1)
        }
        mThreeDayTv.setOnClickListener {
            updateSearchDayUI(mThreeDayTv, 3)
        }
        mSevenSearchTv.setOnClickListener {
            updateSearchDayUI(mSevenSearchTv, 7)
        }
        mMonthSearchTv.setOnClickListener {
            updateSearchDayUI(mMonthSearchTv, 30)
        }
        RxView.clicks(mFilterSearchTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                //确认搜索筛选
                getOrderDBList()
            }
        RxView.clicks(mChooseDataLayout)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                //时间筛选
                if (mChooseDateDialog == null) mChooseDateDialog = ChooseDateDialog(this@OrderLocalActivity)
                mChooseDateDialog?.setOnChooseDateDialogListener(object : ChooseDateDialog.OnChooseDateDialogListener {
                    override fun hadSelectedCalendar(mStartDateStr: String, mEndDateStr: String) {
                        mStartTimeTv.text = mStartDateStr
                        mEndTimeTv.text = mEndDateStr
                        mDateBegin = mStartDateStr
                        mDateEnd = mEndDateStr
                    }
                })
                mChooseDateDialog?.show()
            }
        mResetFilterTv.setOnClickListener {
            //重置筛选条件
            mSearchMulEt.setText("")
            mPage = 0 //从
            mPageSize = 100 // 一页有几条
            mDateBegin = ""
            mDateEnd = ""
            mSearchDay = 0
            mCurStateUpload = -1//上传状态
            mCurStatePay = 0//支付状态
            mCurPayType = -1//支付类型
            mUploadStateTv.text = "上传状态：全部"
            mPayStateTv.text = "支付状态：全部"
            mPayTypeTv.text = "支付类型：全部"
            mStartTimeTv.text = "开始日期"
            mEndTimeTv.text = "结束日期"
            setSearchTvFalse()
            getOrderDBList()
        }

        RxView.clicks(mPrinterTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (mCurOrderDB != null) {
                    PrinterAll.printOrder(PrintOrderBean.orderDB2PrintOrderBean(mCurOrderDB))
                }
            }

        RxView.clicks(mRefreshTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                mCurOrderDB?.let { refreshOrderStatues01() }
            }

        RxView.clicks(mUploadStateTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                AlertDialog.Builder(this)
                    .setTitle("请选择上传状态:")
                    .setCancelable(true)
                    .setSingleChoiceItems(DataApi.mStateUploadArray, mDialogStateUploadIndex) { dialog, which ->
                        //0:未上传，1:上传成功,2:上传失败
                        mDialogStateUploadIndex = which
                        mCurStateUpload = which - 1
                        mUploadStateTv.text = "上传状态：${DataApi.mStateUploadArray[which]}"
                        dialog.dismiss()
                    }.show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
        RxView.clicks(mPayStateTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                AlertDialog.Builder(this)
                    .setTitle("请选择支付状态:")
                    .setCancelable(true)
                    .setSingleChoiceItems(DataApi.mStatePayArray, mDialogStatePayIndex) { dialog, which ->
                        //0未支付;1支付中;2已支付;3退货;4:反结账;5：取消支付；
                        mDialogStatePayIndex = which
                        mCurStatePay = which
                        mPayStateTv.text = "支付状态：${DataApi.mStatePayArray[mCurStatePay]}"
                        dialog.dismiss()
                    }.show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
        RxView.clicks(mPayTypeTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                AlertDialog.Builder(this)
                    .setTitle("请选择支付状态:")
                    .setCancelable(true)
                    .setSingleChoiceItems(mPayTypeArray, mDialogPayTypeIndex) { dialog, which ->
                        //0未支付;1支付中;2已支付;3退货;4:反结账;5：取消支付；
                        mDialogPayTypeIndex = which
                        val payButton = mPayTypeList[which]
                        mCurPayType =
                            if (payButton.pay_id == -1) -1
                            else OrderApi.getLocalPayType(payButton.pay_id)
                        mPayTypeTv.text = "支付类型：${mPayTypeArray[which]}"
                        dialog.dismiss()
                    }.show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
    }

    private var mDialogStateUploadIndex = 0
    private var mDialogStatePayIndex = 0
    private var mDialogPayTypeIndex = 0
    private var mPayTypeList = CommUtils.gson.fromJson<MutableList<PayButton>>(CommUtils.gson.toJson(DataApi.mPayButtonList), object : TypeToken<MutableList<PayButton>>() {}.type)
        .apply { add(0, PayButton().apply { title = "全部";pay_id = -1 }) }
    private var mPayTypeArray = mPayTypeList.map { it.title }.toTypedArray()

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshOrderStatues01() {
        if (!DataApi.mIsConnectNet) return
        //这里针对现金支付，需要提交订单
        if (mCurOrderDB != null && mCurOrderDB?.payType == PAY_TYPE_CASH.toString() && mCurOrderDB?.uploadStatus == 0) {
            var sob = OrderApi.toServerOrderBean(mCurOrderDB!!)
            NormalApi.postPay(
                sortedMapOf(
                    Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                    Params.d_price to mCurOrderDB?.giftPrice, Params.gd_price to mCurOrderDB?.totalGiftPrice, Params.diff_price to mCurOrderDB?.findZero,
                    Params.d_c to String.format("%.2f", (mCurOrderDB?.discountPercent ?: 0) / 100.0),
                    Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg
                ), Urls.pay
            )
                .compose(RxUtils.aLifecycle(this))
                .compose(RxUtils.io())
                .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                        var data = t.data!!
                        //把订单状态改成已支付。
                        mCurOrderDB?.uploadStatus = 1
                        mCurOrderDB?.orderStatus = OrderApi.ORDER_STATUS_PAID
                        //这里应该还需要保存 积分二维码.
                        mCurOrderDB?.integralUrl = data.integral_url
                        App.mDaoSession?.orderDBDao?.update(mCurOrderDB)
                        mSearchAdapter.notifyDataSetChanged()
                        mProductAdapter.notifyDataSetChanged()
                    }
                })
            return
        }
        if (mCurOrderDB?.orderStatus != ORDER_STATUS_PAID) {
            NormalApi.postPay(sortedMapOf(Params.od_n to mCurOrderDB?.orderSn), Urls.orderQuery)
                .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                        var data = t.data!!
                        //订单状态 0 未支付 1已支付 注：状态0时继续轮询，1代表支付成功
                        if (data.od_status == 1) {
                            //修改订单状态
                            mCurOrderDB?.uploadStatus = 1
                            mCurOrderDB?.orderStatus = ORDER_STATUS_PAID
                            App.mDaoSession?.orderDBDao?.update(mCurOrderDB)
                            mSearchAdapter.notifyDataSetChanged()
                            mProductAdapter.notifyDataSetChanged()
                        }
                    }
                })
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshOrderStatues02() {
        if (!DataApi.mIsConnectNet) return
        //这里针对现金支付，需要提交订单
        if (mCurOrderDB != null && mCurOrderDB?.payType == PAY_TYPE_CASH.toString() && mCurOrderDB?.uploadStatus == 0) {
            var sob = OrderApi.toServerOrderBean(mCurOrderDB!!)
            NormalApi.postPay(
                sortedMapOf(
                    Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                    Params.d_price to mCurOrderDB?.giftPrice, Params.gd_price to mCurOrderDB?.totalGiftPrice, Params.diff_price to mCurOrderDB?.findZero,
                    Params.d_c to String.format("%.2f", (mCurOrderDB?.discountPercent ?: 0) / 100.0),
                    Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg
                ), Urls.pay
            )
                .compose(RxUtils.aLifecycle(this))
                .compose(RxUtils.io())
                .subscribe(object : NormalObserver<ServerOrderResult>() {
                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                        var data = t.data!!
                        //把订单状态改成已支付。
                        mCurOrderDB?.uploadStatus = 1
                        mCurOrderDB?.orderStatus = OrderApi.ORDER_STATUS_PAID
                        //这里应该还需要保存 积分二维码.
                        mCurOrderDB?.integralUrl = data.integral_url
                        App.mDaoSession?.orderDBDao?.update(mCurOrderDB)
                        mSearchAdapter.notifyDataSetChanged()
                        mProductAdapter.notifyDataSetChanged()
                    }
                })
            return
        }
        if (mCurOrderDB?.orderStatus != ORDER_STATUS_PAID) {
            NormalApi.postPay(sortedMapOf(Params.od_n to mCurOrderDB?.orderSn), Urls.orderQuery)
                .subscribe(object : NormalObserver<ServerOrderResult>() {

                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                        var data = t.data!!
                        //订单状态 0 未支付 1已支付 注：状态0时继续轮询，1代表支付成功
                        if (data.od_status == 1) {
                            //修改订单状态
                            mCurOrderDB?.uploadStatus = 1
                            mCurOrderDB?.orderStatus = ORDER_STATUS_PAID
                            App.mDaoSession?.orderDBDao?.update(mCurOrderDB)
                            mSearchAdapter.notifyDataSetChanged()
                            mProductAdapter.notifyDataSetChanged()
                        }
                    }
                })
        }
    }

    private fun loadMore() {
        getOrderDBList(false)
    }

    private fun updateSearchDayUI(searchTv: TextView, day: Int) {
        setSearchTvFalse()
        searchTv.isSelected = mSearchDay != day
        mSearchDay = if (searchTv.isSelected) day else 0
    }

    private fun setSearchTvFalse() {
        mTodaySearchTv.isSelected = false
        mThreeDayTv.isSelected = false
        mSevenSearchTv.isSelected = false
        mMonthSearchTv.isSelected = false
    }

    private fun initEasyFloat() {
        //ToastUtil.showToast("isOpenFloat:$isOpenFloat")
        if (PermissionUtils.checkPermission(this)) {
            showEasyFloat()
        } else {
            AlertDialog.Builder(this)
                .setMessage("使用浮窗功能，需要您授权悬浮窗权限。")
                .setPositiveButton("去开启") { _, _ ->
                    showEasyFloat()
                }
                .setNegativeButton("取消") { _, _ -> }
                .show().apply {
                    DialogUtil.hideNavigationBar(this.window)
                }
        }
    }

    private fun showEasyFloat() {
        EasyFloat.with(App.context!!)
            .setLayout(R.layout.float_key_board) {
                it.findViewById<MyKeyBoardViewFlow>(R.id.keyboard_view).apply {
                    if (mKeyboardUtilFlow == null) mKeyboardUtilFlow = KeyboardUtilFlow(this@OrderLocalActivity, this)
                    mKeyboardUtilFlow?.attachTo(mSearchMulEt)
                    mKeyboardUtilFlow?.setOnKeyBoardUtilsFlowListener {
                        getOrderDBList()
                    }
                }
            }
            .setTag(mFloatTag)
            .setShowPattern(ShowPattern.FOREGROUND)
            .setLocation(mSearchMulEt.x.toInt() + mSearchMulEt.width / 2, mSearchMulEt.bottom + mSearchMulEt.height)
            .setAnimator(null)
            .show()
        //d("x:${mSearchMulEt.x};y:${mSearchMulEt.y};bottom:${mSearchMulEt.bottom}")
        if (mKeyboardUtilFlow != null) mKeyboardUtilFlow?.attachTo(mSearchMulEt)
    }

    /*搜索列表 适配器*/
    inner class SearchAdapter : BaseMultiItemQuickAdapter<OrderDB, BaseViewHolder>(null) {

        init {
            addItemType(0, R.layout.item_order_local_search_unselected)
            addItemType(1, R.layout.item_order_local_search_selected)
        }

        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: OrderDB) {
//            if (item.isSelected) {
//                helper.getView<View>(R.id.item_root_view).setBackgroundColor(R.drawable.shape_light_blue)
//            } else {
//                helper.getView<View>(R.id.item_root_view).setBackgroundColor(R.drawable.shape_white_6f)
//            }
            helper
                .setText(R.id.item_tv1, item.orderSn)
                .setText(R.id.item_tv5, item.payTimeName.toString())
                .setText(R.id.item_tv6, "实付￥${item.realPrice ?: 0}")
                .setGone(R.id.item_tv2, item.uploadStatus != 1)
                .setGone(R.id.item_tv3, item.orderStatus == ORDER_STATUS_PAYING)//0未支付;1支付中;2已支付;3退货;4:反结账;5：取消支付；
//                .getView<View>(R.id.item_root_view).apply {
//                    this.isSelected = mData[helper.bindingAdapterPosition].isSelected
//                }


            RxView.clicks(helper.itemView)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe {
                    mData.forEach { it.item_type = 0 }
                    val orderDB = mData[helper.bindingAdapterPosition]
                    orderDB.item_type = 1
                    notifyDataSetChanged()
                    updateOrderInfo(orderDB)
                    refreshOrderStatues02()
                }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateOrderInfo(orderDB: OrderDB?) {
        mCurOrderDB = orderDB
        var total = 0.0 //商品总额
        var totalGift = 0.0 //商品总优惠
        val orderProductDBList = try {
            orderDB?.orderProductDBList
        } catch (e: Exception) {
            null
        }
        orderProductDBList?.forEach {
            total += try {
                (it.realPrice.toDouble() * it.weight.toDouble())
            } catch (e: Exception) {
                0.0
            }
            totalGift += try {
                it.giftPrice.toDouble()
            } catch (e: Exception) {
                0.0
            }
        }

        //刷新右边数据
        mProductAdapter.setNewData(orderProductDBList)
        mOrderSnTv.text = orderDB?.orderSn.isNotAvailable()
        mOrderTimeTv.text = orderDB?.id?.toString().isNotAvailable()
        mOrderCreateTimeTv.text = orderDB?.createTimeName?.toString().isNotAvailable()
        mOrderOperationUserTv.text = orderDB?.userName.toString().isNotAvailable()
        mOrderPriceTv.text = "商品总额：￥${String.format("%.2f", total)}；订单总金额：￥${orderDB?.totalPrice ?: "0.00"}"

        var discountPercent = if (orderDB?.discountPercent == 100) "" else "(${String.format("%.1f", (orderDB?.discountPercent ?: 100) / 10.0)}折)"
        mOrderDiscountTv.text = "商品优惠：￥${String.format("%.2f", totalGift) ?: 0}；整单优惠${discountPercent}：￥${orderDB?.giftPrice ?: "0.00"}"

        var findZero = try {
            (orderDB?.findZero ?: "0.0").toDouble()
        } catch (e: Exception) {
            0.0
        }
        var fz = if (findZero == 0.0) "" else ", 找零￥${findZero}"
        mOrderRealPriceTv.text = "${orderDB?.payTypeName ?: ' '}￥${orderDB?.realPrice ?: 0}${fz}"
        mPrinterTv.visibility = if (orderDB == null) View.GONE else View.VISIBLE
    }

    /*商品列表 适配器*/
    inner class ProductAdapter : BaseQuickAdapter<OrderProductDB, BaseViewHolder>(R.layout.item_order_local_product, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: OrderProductDB) {
            var discount = if (item.discountPercent == 100) "" else " (折后${String.format("%.2f", item.discountPercent / 100.0 * (item.realPrice?.toDouble() ?: 0.0))})"
            helper
                .setText(R.id.item_tv1, (helper.bindingAdapterPosition + 1).toString())
                .setText(R.id.item_tv2, item.productName)
                .setText(R.id.item_tv3, item.weight/*.plus("/")*/.plus(item.unitName))
                .setText(R.id.item_tv4, String.format("%.2f", item.realPrice?.toDouble() ?: 0.0).plus(discount))
                .setText(R.id.item_tv5, String.format("%.2f", item.subTotalPrice?.toDouble() ?: 0.0))
                .setText(R.id.item_tv6, String.format("%.2f", item.giftPrice?.toDouble() ?: 0.0))
                .getView<View>(R.id.item_root_view).apply {
                    setBackgroundColor(if (helper.bindingAdapterPosition % 2 == 0) CommUtils.getColor(R.color.GC9E2F3) else CommUtils.getColor(R.color.grey_EBF3FB))
                }
        }
    }

    override fun onDestroy() {
        if (EasyFloat.isShow(mFloatTag)) EasyFloat.dismiss(mFloatTag)
        EasyFloat.dismiss(mFloatTag)
        super.onDestroy()
    }

}